package com.huluobo.mvvm_base.mvvm.net;

import android.content.SharedPreferences;

import com.blankj.utilcode.util.SPUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 网络连接管理类,使用单例模式创建网络请求工具,懒汉模式
 * Created by LC on 2024/2/22.
 */
public class RetrofitManager {
    private static volatile RetrofitManager retrofitManager;

    private Retrofit retrofit;

    //私有化构造方法,单例模式核心
    private RetrofitManager() {
    }

    //使用懒汉模式对外暴露实例
    public static RetrofitManager getInstance() {
        if (retrofitManager == null) {
            //使用同步锁,保证线程同步
            synchronized (RetrofitManager.class) {
                if (retrofitManager == null) {
                    retrofitManager = new RetrofitManager();
                }
            }
        }
        return retrofitManager;
    }

    //对外提供Retrofit
    public Retrofit getRetrofit() {
        if (retrofit == null) {
            retrofit = createRetrofit();
        }
        return retrofit;
    }

    //创建Retrofit网络工具
    private Retrofit createRetrofit() {
        OkHttpClient.Builder okhttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                //给所有的网络请求中的Header中添加Token,不需要的位置不用管,需要的位置,会自动读取token
                .addInterceptor(new Interceptor() {
                    //添加token拦截器,所有的网络请求中会附加一个header中的token,方便请求的时候直接用
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        String token = SPUtils.getInstance().getString(Const.SP_TOKEN);//拿到sp中存储的token
                        Request.Builder newBuilder = chain.request().newBuilder();
                        newBuilder.addHeader(Const.PARAM_TOKEN, token);
                        return chain.proceed(newBuilder.build());
                    }
                });

        Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                .baseUrl(Const.BASE_URL)
                .client(okhttpClient.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());

        return retrofitBuilder.build();
    }

}
